# 数据库操作管理器（线程安全版）
import os
import time
import pymysql # 改用PyMySQL
import threading
from pymysql import Error as MySQLError  # 修改错误导入
from dotenv import load_dotenv
from dbutils.pooled_db import PooledDB
from datetime import date
from typing import List, Dict, Optional

load_dotenv()

class MySQLDatabaseManager:
    """MySQL数据库连接池管理器"""

    _pool = None
    _lock = threading.Lock()

    @classmethod
    def close_all_connections(cls):
        with cls._lock:
            if cls._pool:
                cls._pool.close()
                cls._pool = None

    def __init__(self, max_retries: int = 3):
        self.retries = 0
        self.max_retries = max_retries
        self._connect()

    def _connect(self):
        while self.retries < self.max_retries:
            try:
                with MySQLDatabaseManager._lock:
                    if not MySQLDatabaseManager._pool:
                        MySQLDatabaseManager._create_pool()

                    self.conn = MySQLDatabaseManager._pool.connection()
                    self.cursor = self.conn.cursor()
                    self.cursor.execute("SELECT 1")  # 连接测试
                    break
            except (MySQLError, IndexError) as e:
                self.retries += 1
                if self.retries == self.max_retries:
                    raise ConnectionError(f"数据库连接失败，重试{self.max_retries}次后仍然失败: {str(e)}")
                time.sleep(min(2 ** self.retries, 10))

    @classmethod
    def _create_pool(cls) -> None:
        try:
            _pool = PooledDB(
                creator=mysql.connector.connect,  # 使用PyMySQL
                host=os.getenv("DB_HOST", "localhost"),
                port=int(os.getenv("DB_PORT", "3306")),
                user=os.getenv("DB_USER", "root"),
                password=os.getenv("DB_PASSWORD", ""),
                database=os.getenv("DB_NAME", "calendar_db"),
                autocommit=True,
                connect_timeout=5,
                maxconnections=10,
                failures=(MySQLError,),
                threadlocal=True  # 明确启用线程安全
            )
        except Exception as e:
            raise ConnectionError(f"数据库连接池创建失败: {str(e)}")

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        try:
            if self.cursor:
                self.cursor.close()
            if self.conn:
                self.conn.close()
        except Exception:
            pass
